import React, {Fragment, useEffect, useState} from "react";
import {Button, Checkbox, Col, Form, Input, message, Row} from "antd";
import {getCaptchaImage} from "../api/captchaImage";
import {login} from "../api/login";
import {useNavigate} from "react-router-dom";
import './css/login.css'
import background from '../../src/imgs/back.jpg'

export function Login() {
    const [url, setUrl] = useState('')
    const [uuid, setUuid] = useState('')
    const [remember, setRemember] = useState(false)
    const [loading, setLoading] = useState(false)
    const [messageApi, contextHolder] = message.useMessage();
    const navigate = useNavigate()
    // 判断是否已经登录
    useEffect(() => {
        if (localStorage.getItem('token') || sessionStorage.getItem('token')) {
            messageApi
                .open({type: 'success', content: '您已登录'})
            setTimeout(() => {
                navigate('/home')
            }, 500)
        }
    }, []);
    //获取验证码
    useEffect(() => {
        setCaptchaImage()
    }, []);
    //点击验证码重置
    const getCode = () => {
        setCaptchaImage()
    }
    //设置验证码
    const setCaptchaImage = () => {
        getCaptchaImage().then(res => {
            setUrl('data:image/gif;base64,' + res.data.img)
            setUuid(res.data.uuid)
        })
    }
    // 选中记住我
    const handleRemember = (e) => {
        setRemember(e.target.checked)
    }
    //表单填写完毕提交
    const onFinish = (values) => {
        setLoading(true)
        const loginBody = {...values, uuid}
        // 登录
        login(loginBody).then(res => {
            if (res.data.code === 200) {
                messageApi.open({
                    type: 'success',
                    content: '登录成功~',
                }).then(() => {
                    //设置token 记录在sessionStorage中
                    sessionStorage.setItem('token', res.data.token)
                    // 如果勾选记住我 那么就记录在localStorage
                    if (remember) {
                        localStorage.setItem('token', res.data.token)
                    }
                    setTimeout(() => {
                        location.reload()
                        setLoading(false)
                        navigate('/blog')
                    }, 300)
                })
            } else {
                messageApi.open({
                    type: 'error',
                    content: '登录失败,' + res.data.msg,
                });
                setLoading(false)
                getCode() // 重置验证码
            }
        }).catch(err => {
            messageApi.open({
                type: 'error',
                content: '登录失败!' + err.msg,
            });
            setLoading(false)
            getCode() // 重置验证码
        })
    };
    return <Fragment>
        <Row>
            <Col span={12}>
                <div className="login-img">
                    <img src={background} alt=""
                         style={{width: '100%', height: '100%', borderRadius: '30px', border: "1px solid #2b2b2b"}}/>
                </div>
            </Col>
            <Col span={12}>
                <div className="login-background">
                    {contextHolder}
                    <div className="login-info">
                        <h1>欢迎来到TianMing博客</h1>
                    </div>
                    <Row justify={"center"}>
                        <div className="login-body">
                            <Form
                                name="basic"
                                labelCol={{
                                    span: 6,
                                }}
                                wrapperCol={{
                                    span: 18,
                                }}
                                style={{
                                    maxWidth: 750,
                                }}
                                initialValues={{
                                    remember: false,
                                }}
                                onFinish={onFinish}
                                autoComplete="off">
                                <Form.Item
                                    label="用户名"
                                    name="username"
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入用户名!',
                                        },
                                    ]}>
                                    <Input/>
                                </Form.Item>
                                <Form.Item
                                    label="密码"
                                    name="password"
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入密码!',
                                        },
                                    ]}
                                >
                                    <Input.Password/>
                                </Form.Item>
                                <Form.Item label="验证码"
                                           name="code"
                                           rules={[
                                               {
                                                   required: true,
                                                   message: '请输入验证码!',
                                               },
                                           ]}>
                                    <Row>
                                        <Col span={15}>
                                            <Input/>
                                        </Col>
                                        <Col span={9}>
                                            <img src={url} onClick={getCode} style={{height: '38px', width: '95px'}}
                                                 alt=""/>
                                        </Col>
                                    </Row>
                                </Form.Item>
                                <Form.Item
                                    name="remember"
                                    valuePropName="checked"
                                    wrapperCol={{
                                        offset: 5,
                                        span: 19,
                                    }}
                                >
                                    <Checkbox value={remember} onChange={(e) => handleRemember(e)}>记住我</Checkbox>
                                </Form.Item>
                                <Form.Item
                                    wrapperCol={{
                                        offset: 5,
                                        span: 19,
                                    }}
                                >
                                    <Row justify={"center"} gutter={12}>
                                        <Col>
                                            <Button type="primary" htmlType="submit" loading={loading}>
                                                提交
                                            </Button>
                                        </Col>
                                        <Col>
                                            <Button type="default">
                                                重置
                                            </Button>
                                        </Col>
                                    </Row>
                                </Form.Item>
                            </Form>
                        </div>
                    </Row>
                </div>
            </Col>
        </Row>
    </Fragment>
}